package com.homedo.odin.solution.config.aspect;

import com.alibaba.fastjson.JSONObject;
import com.homedo.core.common.exception.BizException;
import java.util.Arrays;
import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * Created by donglibing 2018/3/20 日志切面
 */
@Aspect
@Component
public class LogAspect {

    private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);

    @Pointcut("execution(public * com.homedo.odin.solution.controller.*.*.*(..))")
    public void webLog() {
    }

    @Before("webLog()")
    public void deBefore(JoinPoint joinPoint) throws Throwable {
        HttpServletRequest request = getHttpServletRequest();

        StringBuilder sb = new StringBuilder();
        sb.append("---接口请求---").append("    URL:" + request.getRequestURL().toString())
                .append("   requestMethod: " + request.getMethod())
                .append("   IP: " + request.getRemoteAddr())
                .append("   args: " + Arrays.toString(joinPoint.getArgs()));
        logger.info(sb.toString());
    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(JoinPoint jp,Object ret) throws Throwable {
        // 接收到请求，记录请求内容
        HttpServletRequest request = getHttpServletRequest();

        StringBuilder sb = new StringBuilder();
        sb.append("---接口返回---").append("    URL:" + request.getRequestURL().toString())
                .append("  result :" + JSONObject.toJSONString(ret));

        // 处理完请求，返回内容
        logger.info(sb.toString());
    }

    //后置异常通知
    @AfterThrowing(pointcut = "webLog()", throwing = "e")
    public void throwss(JoinPoint jp, Throwable e) {
        // 接收到请求，记录请求内容
        HttpServletRequest request = getHttpServletRequest();

        String erro = e.getMessage() == null ? "" : e.getMessage();
        //区分业务异常系统异常
        if (e instanceof BizException) {
            logger.info("业务异常: {}", erro);
        } else {
            logger.error("---接口错误---URL:{}",request.getRequestURL().toString());
            logger.error("系统异常: {}", e);
        }
    }

    //后置最终通知,final增强，不管是抛出异常或者正常退出都会执行
    @After("webLog()")
    public void after(JoinPoint jp) {

    }

    /*//环绕通知,环绕增强，相当于MethodInterceptor
    @Around("webLog()")
    public Object arround(ProceedingJoinPoint pjp) {
        System.out.println("方法环绕start.....");
        try {
            Object o =  pjp.proceed();
            System.out.println("方法环绕proceed，结果是 :" + o);
            return o;
        } catch (Throwable e) {
            e.printStackTrace();
            return null;
        }
    }*/

    private HttpServletRequest getHttpServletRequest() {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attributes.getRequest();
    }

}
